package cn.neusoft.service.impl;

import cn.neusoft.bean.Food;
import cn.neusoft.dao.IFoodDao;
import cn.neusoft.dao.impl.FoodDao;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.service.IFoodService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.alibaba.druid.util.StringUtils;

import java.util.List;

public class FoodService implements IFoodService {
    private IFoodDao foodDao;
    public FoodService(){
        foodDao=new FoodDao();
    }

    @Override
    public ResultBean add(Food food) throws Exception {
        if(food==null||
                StringUtils.isEmpty(food.getFoodName())){
            return ResultBean.ERROR(10001,"params null");
        }
        int i=foodDao.add(food);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("add food fail");
    }

    @Override
    public ResultBean update(Food food) throws Exception {
        if(food==null||
        food.getFoodId()==null||
        StringUtils.isEmpty(food.getFoodName())){
            return  ResultBean.ERROR(10001,"params null");
        }
        int i=foodDao.update(food);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("update food fail");
    }

    @Override
    public ResultBean delete(Integer id) throws Exception {
        if(id==null){
            return ResultBean.ERROR(10001,"params null");       }
        int i=foodDao.delete(id);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("delete food fail");
    }

    @Override
    public ResultBean getById(Integer id) throws Exception {
        if(id==null){
            return ResultBean.ERROR(10001,"params null");       }
        Food food=foodDao.getById(id);
        return food!=null?ResultBean.SUCCESS(food):ResultBean.ERROR("select food by id fail");
    }

    @Override
    public ResultBean getAll() throws Exception {
        List<Food> foodList=foodDao.getAll();
        return foodList!=null?ResultBean.SUCCESS(foodList):ResultBean.ERROR("select all food fail");
    }

    @Override
    public ResultBean getByPage(BaseQuery baseQuery) throws Exception {
        PageBean<Food> pageBean=new PageBean<>();
        int count= foodDao.getCount(baseQuery);
        pageBean.setTotalRows(count);

        if(count% baseQuery.getPageCount()==0){
            pageBean.setTotalPages(count/baseQuery.getPageCount());
        }else{
            pageBean.setTotalPages(count/baseQuery.getPageCount()+1);
        }

        List<Food> foodList=foodDao.getByPage(baseQuery);
        pageBean.setData(foodList);

        return ResultBean.SUCCESS(pageBean);
    }

    @Override
    public ResultBean batchDel(List<Integer> ids) throws Exception {
        if (ids==null||ids.size()==0){
            return ResultBean.ERROR("params null");
        }
        for (Integer id:ids){
            foodDao.delete(id);
        }


        return ResultBean.SUCCESS();
    }
}
